<template>
  <el-dialog
    :model-value="modelValue"
    width="70%"
    align-center
    draggable
    destroy-on-close
    :show-close="false"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    class="main_notice_message"
    :append-to-body="true"
  >
    <template #header>
      <div class="flex justify-between h-full">
        <strong>
          <i class="text-[#fff] text-[20px]">{{
            list?.messageType?.label || "-"
          }}</i>
        </strong>
        <div class="h-full">
          <img
            :src="list?.messageType?.value == 2 ? system_update : system_edit"
            alt=""
            class="h-full object-fit: cover"
          />
        </div>
      </div>
    </template>
    <div
      v-loading="loading"
      style="max-height: 90vh"
      class="overflow-y-auto"
      @scroll="handleScroll"
      ref="scrollContainer"
    >
      <div>
        <div class="font-bold text-[16px] mt-[12px]">
          {{ list?.title || "-" }}
        </div>
        <div class="text-[#999] my-[8px]">
          <span>已读 : <span class="text-[red]">{{ list?.viewed || 0 }} 人</span></span>
          <span class="mx-[20px]">发布人 : {{ list?.createUser || "-" }}</span>
          <span>发布时间 : {{ list?.sendTime || "-" }}</span>
        </div>
        <div
          @click="imageChangeEdit"
          v-html="list?.content || '-'"
          class="w-full py-[8px]"
        ></div>
        <!-- border-b border-t border-[#e5e7eb] -->
        <div>
          <!-- <strong>附件</strong> -->
          <p v-for="item in list?.file || []" :key="item" class="my-[4px]">
            <svg-icon
              icon-class="file"
              class="inline-block text-[#3487FF] mr-[2px]"
            ></svg-icon>
            <span>{{ item.name }}</span>
            <span
              class="mx-[16px] text-[#3487FF] cursor-pointer"
              @click.stop="handleDown(item.url)"
              >下载</span
            >
          </p>
        </div>
      </div>
    </div>
    <template #footer>
      <span class="text-[#333] mr-[12px] text-[14px]" v-if="sum.total > 1">{{
        `(${sum.current}/${sum.total})`
      }}</span>
      <el-button
        v-if="sum.total > 1"
        @click="handlePre"
        type="primary"
        :disabled="sum.preDis"
      >
        上一条 {{ buttonText }}
      </el-button>
      <el-button
        v-if="sum.total > 1"
        @click="handleNext"
        type="primary"
        :disabled="sum.nextDis"
      >
        下一条 {{ buttonText }}
      </el-button>
      <el-button
        v-if="sum.current == sum.total"
        @click="handleClose"
        :disabled="sum.closeDis"
      >
        关闭 {{ buttonText }}
      </el-button>
    </template>
  </el-dialog>
  <ImagePreview
    :isPreview="isPreview"
    :previewSrc="previewSrc"
    @update:isPreview="(val) => (isPreview = val)"
  />
</template>

<script setup>
import { ref, watch, reactive, toRefs, onUnmounted } from "vue";
import { ElMessage } from "element-plus";
import {
  messageDetails,
  messageView,
  downFlieMsg,
} from "@/api/system/notice.js";
import system_edit from "@/assets/images/system_edit.png";
import system_update from "@/assets/images/system_update.png";
import ImagePreview from "@/components/imageViewer/index.vue";
const props = defineProps({
  modelValue: { type: Boolean, default: false },
  data: { type: [Array, Object], default: () => [] },
});
const { data } = toRefs(props);
const sum = reactive({
  pre: 0,
  total: 0,
  next: 0,
  current: 0,
  preDis: false,
  nextDis: false,
  closeDis: false,
});
const list = ref({});
const countdownTime = ref(10);
const buttonText = ref("");
let timer = null;
const loading = ref(false);
const emit = defineEmits(["update:modelValue", "close"]);

const scrollContainer = ref(null);
watch(
  () => data.value,
  (val) => {
    // console.log(val);
    if (val?.length) {
      initializeValues(val);
    } else {
      list.value = {};
    }
  }
);

const initializeValues = (val) => {
  sum.pre = 1;
  sum.current = 1;
  sum.preDis = true;
  sum.total = val.length;
  sum.next = val.length === 1 ? 1 : 2;
  sum.preDis = val.length === 1;

  list.value = val[0];
  handleCountdown(list.value.popLevel.value);
};

const handleCountdown = (popLevel) => {
  if (popLevel === 3) {
    sum.preDis = true;
    sum.nextDis = true;
    sum.closeDis = true;
    return;
  }
  if (popLevel === 2) {
    countdownTime.value = 10;
  } else if (popLevel === 4) {
    countdownTime.value = 60;
  } else {
    countdownTime.value = 0;
  }
  startCountdown();
};

const startCountdown = () => {
  sum.preDis = true;
  sum.nextDis = true;
  sum.closeDis = true;
  buttonText.value = `${countdownTime.value} s`;

  timer = setInterval(() => {
    countdownTime.value -= 1;
    buttonText.value =
      countdownTime.value >= 0 ? `${countdownTime.value} s` : "";
    if (countdownTime.value < 0) {
      clearInterval(timer);
      sum.closeDis = false;
      sum.preDis = sum.current === 1;
      sum.nextDis = sum.current === sum.total;
    }
  }, 1000);
};

const handlePre = () => {
  if (sum.current === 1) return;
  changeCurrentItem(-1);
};

const handleNext = () => {
  if (sum.current === sum.total) return;
  changeCurrentItem(1);
};

const changeCurrentItem = (delta) => {
  const index = data.value.findIndex((item) => item.id === list.value.id);
  list.value = data.value[index + delta];
  sum.current += delta;
  sum.pre = sum.current - 1 > 0 ? sum.current - 1 : 1;
  sum.next = sum.current + 1 > sum.total ? sum.total : sum.current + 1;
  sum.preDis = sum.current === 1;
  sum.nextDis = sum.current === sum.total;
  handleCountdown(list.value.popLevel.value);
  scrollToTop();
  setTimeout(() => {
    checkScroll();
  }, 1000);
};

const scrollToTop = () => {
  const container = scrollContainer.value;
  container.scrollTo({
    top: 0,
    behavior: "smooth",
  });
};

const checkScroll = () => {
  if (list.value.popLevel.value != 3) return;
  const container = scrollContainer.value;
  if (container.scrollHeight <= container.clientHeight) {
    sum.closeDis = false;
    sum.preDis = sum.current === 1;
    sum.nextDis = sum.current === sum.total;
  } else {
    sum.closeDis = true;
    sum.preDis = true;
    sum.nextDis = true;
  }
};

const handleScroll = (event) => {
  if (list.value.popLevel.value != 3) return;
  const { scrollTop, scrollHeight, clientHeight } = event.target;
  if (scrollTop + clientHeight + 10 >= scrollHeight) {
    sum.closeDis = false;
    sum.preDis = sum.current === 1;
    sum.nextDis = sum.current === sum.total;
  }
};
const handleDown = async (_url) => {
  const { data } = await downFlieMsg({
    alias: "notice-message-private",
    fileKey: _url,
  });
  if (data) window.open(data, "noopener", "noreferrer");
};

onUnmounted(() => {
  clearInterval(timer);
});
const viewsMsg = async (ids) => {
  try {
    const { code, message } = await messageView({ ids });
  } catch (error) {}
};

const previewSrc = ref([]);
const isPreview = ref(false);
const imageChangeEdit = (e) => {
  if (e.target.tagName == "IMG") {
    previewSrc.value = e.target.src;
    isPreview.value = true;
  }
};
const handleClose = () => {
  let ids = data.value.map((item) => item.id);
  viewsMsg(ids);
  emit("update:modelValue", false);
  emit("close");
};
</script>
<style lang="scss">
.main_notice_message {
  border-radius: 8px;
  .el-dialog__header {
    border-top-left-radius: 8px;
    border-top-right-radius: 8px;
    background: linear-gradient(to right, #3487ff, #62baff) !important;
    padding-right: 15px;
  }
}
</style>
<style lang="scss" scoped>
:deep(h1) {
  font-size: 2em;
  font-weight: 700;
}
:deep(h2) {
  font-size: 1.5em;
  font-weight: 700;
}
:deep(h3) {
  font-size: 1.17em;
  font-weight: 700;
}
:deep(h4) {
  font-size: 1em;
  font-weight: 700;
}
:deep(h5) {
  font-size: 0.83em;
  font-weight: 700;
}
</style>
